//
//  AppDelegate.m
//  IconMaster
//
//  Created by mac on 2017/7/24.
//  Copyright © 2017年 yangweiwei. All rights reserved.
//

#import "AppDelegate.h"
#import "NavViewController.h"
#import "MongooseDaemon.h"
#import "RMStepsController.h"
#import "ViewController.h"
#import "DBUtil.h"
static BOOL hasOpenUrl = NO;
@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//    NavViewController *nav = [[NavViewController alloc] init];
//    [nav setBarType];
//    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,nil]]; 
//    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"nav_bg.png"] forBarMetrics:UIBarMetricsDefault];
    [MongooseDaemon instance];
//    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"once"]) {
//    } else {
//        [[NSUserDefaults standardUserDefaults] setObject:@"once" forKey:@"once"];
//    }
    // Override point for customization after application launch.
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    NSLog(@"did enter background");
    [self showBlankOverlayController];
    
    self.taskID =
    [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[MongooseDaemon instance] stopMongooseDaemon];
        [[UIApplication sharedApplication] endBackgroundTask:self.taskID];
    }];
    
    [DBUtil closeDBIfNeed];
}
- (void)showBlankOverlayController
{
//    if ([[self.navigationController topViewController] isKindOfClass:[PasswordViewController class]] ||
//        [[self.navigationController topViewController] isKindOfClass:[BlankViewController class]]) {
//        
//    } else {
        UIViewController* controller = [[ViewController alloc] init];
        [self.navigationController pushViewController:controller animated:NO];
//    }
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    NSLog(@"did become active");
    [[MongooseDaemon instance] startMongooseDaemon:@"8080"];
    if (hasOpenUrl) {
        hasOpenUrl = NO;
    } else {
//        [self hideOtherOverlayController];
    }
    //	[self networkCheck];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[MongooseDaemon instance] stopMongooseDaemon];
//    theDelegate = NULL;
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    NSLog(@"open URL");
    hasOpenUrl = YES;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
       	NSString* pathString = [url absoluteString];
        pathString = GetStringFromScheme(pathString);
        
        CComposedUrl* composedUrl = [[CComposedUrl alloc] initWithString:pathString];
        if (composedUrl.password) {
//            PasswordViewController* controller = [[PasswordViewController alloc] init];
//            controller.password = composedUrl.password;
//            controller.realUrl = composedUrl.realUrl;
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self.navigationController pushViewController:controller	animated:NO];
//            });
        } else {
//            dispatch_async(dispatch_get_main_queue(), ^{
//                if (self.navigationController && [[self.navigationController topViewController] isKindOfClass:[BlankViewController class]] ) {
//                    
//                } else {
//                    [self showBlankOverlayController];
//                }
//            });
            
            NSURL* url = [NSURL URLWithString:composedUrl.realUrl];
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                //
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSString* msg = [NSString stringWithFormat:NSLocalizedString(@"Can not open %@(%@)", @""), composedUrl.title, composedUrl.realUrl];
                    if (!success) {
                        //                    [self hideOtherOverlayController];
                        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil message:msg delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", @"") otherButtonTitles: nil];
                        [alert show];
                    } else {
                        //                    exit(0);
                    }
                });
                exit(0);
            }];
       
        }
    });
     
    return YES;
}

@end
